package com.travel.travelServer.utils;

import com.travel.travelServer.entity.User;
import com.travel.travelServer.mapper.UserMapper;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Resource
    private RedisUtil redisUtil;

    @Resource
    private UserMapper userMapper;

    @Value("${token.header}")
    private String tokenHeader;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader(tokenHeader);
        if (!StringUtils.hasText(token)){
            filterChain.doFilter(request,response);
            return;
        }
        // 解析token
        Claims claims = JWTUtils.parseToken(token);
        String userId = claims.getSubject();
        // 从redis中获取用户信息
//        String redisKey = "login:" + userId;
//        Object o = redisUtil.getExpire(redisKey);
//        LoginUser loginUser = JSONObject.parseObject(JSON.toJSONString(o), LoginUser.class);
//        if (Objects.isNull(loginUser)){
//            throw new ServiceException("用户未登录");
//        }
        // 存入securityContextHolder
        User user = userMapper.selectById(userId);
        // todo 获取权限信息封装到authentication中
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(user,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
